from bokeh.palettes import Spectral5
from bokeh.sampledata.autompg import autompg as df
from bokeh.transform import factor_cmap
from bokeh.sampledata.autompg import autompg_clean as df
from bokeh.plotting import figure

from pyecharts import options as opts
from pyecharts.charts import Geo
from pyecharts.faker import Faker
from pyecharts.charts import Bar, Grid, Line, Pie, Tab, Map, Page
from pyecharts.charts import WordCloud
from pyecharts.globals import SymbolType
import pandas as pd

from flask import Flask,render_template
import json

def mpg():
    '''
    Manufacturer grouped by # Cylinders
    '''
    df.cyl = df.cyl.astype(str)
    # df.yr = df.yr.astype(str)
    group = df.groupby(['cyl', 'mfr'])  # 复合条件分组，[缸数、厂家]
    index_cmap = factor_cmap('cyl_mfr', palette=Spectral5, factors=sorted(df.cyl.unique()), end=1)
    # 画布
    p = figure(plot_width=1000, plot_height=500, title="Mean MPG by # Cylinders and Manufacturer",
               x_range=group, tooltips=[("MPG", "@mpg_mean"), ("Cyl, Mfr", "@cyl_mfr")])
    # 绘图
    p.vbar(x='cyl_mfr', top='mpg_mean', width=1, source=group,
           line_color="white", fill_color=index_cmap, )  # 尾气排放量均值
    # 其他
    p.y_range.start = 0
    p.x_range.range_padding = 0.05  # 同css中的padding
    p.xgrid.grid_line_color = None
    p.xaxis.axis_label = "Manufacturer grouped by # Cylinders"
    p.xaxis.major_label_orientation = 1.2  # x轴标签旋转
    p.outline_line_color = None

    return p


def vbar_demo():
    p = figure(plot_width=300, plot_height=300)
    p.vbar(
        x=[1, 2, 3, 4],
        width=0.5,
        bottom=0,
        top=[1.7, 2.2, 4.6, 3.9],
        color='navy'
    )
    return p

def geo_map(data):
    c = (
        Geo()
            .add_schema(maptype="china")
            .add("geo", [list(z) for z in zip(Faker.provinces, Faker.values())])
            .set_series_opts(
            label_opts=opts.LabelOpts(is_show=False))
            .set_global_opts(
            visualmap_opts=opts.VisualMapOpts(), title_opts=opts.TitleOpts(title="Geo-基本示例")
            )
        )
    return c

def Geographical_distribution():
    df1 = pd.read_excel('服饰行业粉丝地域分布.xlsx')
    fs_dy = df1.groupby('省份')['占比'].mean().reset_index()
    c = (
        Map()
            .add("省份/占比", [list(i) for i in zip(fs_dy['省份'].tolist(), fs_dy['占比'].tolist())], "china")
            .set_global_opts(
            title_opts=opts.TitleOpts(title="粉丝地域分布"),
            visualmap_opts=opts.VisualMapOpts(
                max_=10),
            # 工具栏
            toolbox_opts=opts.ToolboxOpts(
                pos_left="90%")
        )
    )
    c.render("粉丝分布地图.html")

def Active_time():
    df2 = pd.read_excel('服饰行业粉丝活跃时间分布.xlsx')
    df2_week = df2[df2['type'] == 'week']    # 筛选出周数据
    active_week = df2_week.groupby('name')['占比'].mean().reset_index()    # 汇总不同品类同一天的占比平均值
    active_week['占比'] = round(active_week['占比'], 2)  # round()四舍五入保留四位小数

    df2_hour = df2[df2['type'] == 'hour']    # 筛选出小时数据
    active_hour = df2_hour.groupby('name')['占比'].mean().reset_index()    # 汇总不同品类同一小时的占比平均值
    active_hour['占比'] = round(active_hour['占比'], 2)

    x_data_week = active_week['name'].tolist()
    y_data_week = active_week['占比'].tolist()
    x_data_hour = active_hour['name'].tolist()
    y_data_hour = active_hour['占比'].tolist()

    def fan_week() -> Line:
        w = (
            Line()
            .add_xaxis(x_data_week)
            .add_yaxis(
                "活跃度",
                y_data_week,
                markpoint_opts=opts.MarkPointOpts(data=[opts.MarkPointItem(type_="max")]),
            )
            .set_global_opts(
                title_opts=opts.TitleOpts(title="粉丝活跃时间_周"),
                datazoom_opts=[opts.DataZoomOpts()],
            )
        )
        return w

    def fan_hour() -> Line:
        h = (
            Line()
            .add_xaxis(x_data_hour)
            .add_yaxis(
                "活跃度",
                y_data_hour,
                markpoint_opts=opts.MarkPointOpts(data=[opts.MarkPointItem(type_="max")]),
            )
            .set_global_opts(
                title_opts=opts.TitleOpts(title="粉丝活跃时间_小时"),
                datazoom_opts=[opts.DataZoomOpts()],
            )
        )
        return h

    tab = Tab()
    tab.add(fan_week(), "粉丝活跃时间_周")
    tab.add(fan_hour(), "粉丝活跃时间_小时")
    tab.render("粉丝活跃时间.html")

def Focus_point():
    df3 = pd.read_excel('服饰行业粉丝关注焦点.xlsx')
    df_fans = df3.groupby(['标签']).agg({'占比': 'sum'}).reset_index()
    focus_list = df_fans[['标签', '占比']].apply(lambda x: tuple(x), axis=1).values.tolist()

    fan_focus = (
        WordCloud()
            .add(series_name="粉丝关注焦点",
                 data_pair=focus_list,
                 word_size_range=[20, 80],  # 字体大小范围
                 rotate_step=90,  # 文字旋转90°
                 textstyle_opts=opts.TextStyleOpts(font_family="cursive"),
                 )
            .set_global_opts(
            title_opts=opts.TitleOpts(
                title="粉丝关注焦点",
                title_textstyle_opts=opts.TextStyleOpts(font_size=20),
                pos_left='center',
                pos_top='5%'  # 调整标题位置
            ),
            tooltip_opts=opts.TooltipOpts(is_show=True)
            ).render("关注焦点.html")
        )
    return fan_focus

def People_tag():
    df4 = pd.read_excel('服饰行业粉丝人群标签.xlsx')
    df_biaoqian = df4.groupby(['人群标签']).agg({'占比': 'sum'}).reset_index()
    df_biaoqian['占比'] = round(df_biaoqian['占比'], 0)
    renqun_list = df_biaoqian[['人群标签', '占比']].apply(lambda x: tuple(x), axis=1).values.tolist()

    c = (
        Pie()
            .add("", renqun_list)
            .set_global_opts(
            title_opts=opts.TitleOpts(title="粉丝人群标签"),
            legend_opts=opts.LegendOpts(pos_left="15%"),  # 调整位置
        )
            .set_series_opts(label_opts=opts.LabelOpts(formatter="{b}: {c}"))
    ).render("粉丝人群标签.html")
    return c

def Fushi_nianling():
    df5 = pd.read_excel('服饰行业品类分析-大类占比.xlsx')
    product_name = df5['行业名称'].unique()
    industry_list = product_name.tolist()

    c = (
        Bar(init_opts=opts.InitOpts(width='1500xp'))
            .add_xaxis(list(industry_list))
            .add_yaxis("<18岁", list(df5[df5['年龄段'] == '<18']['占比']), stack="年龄段")
            .add_yaxis("18-24岁", list(df5[df5['年龄段'] == '18-24']['占比']), stack="年龄段")
            .add_yaxis("25-34岁", list(df5[df5['年龄段'] == '25-34']['占比']), stack="年龄段")
            .add_yaxis("35-44岁", list(df5[df5['年龄段'] == '35-44']['占比']), stack="年龄段")
            .add_yaxis(">44岁", list(df5[df5['年龄段'] == '>44']['占比']), stack="年龄段")
            .set_series_opts(label_opts=opts.LabelOpts(is_show=False))
            .set_global_opts(title_opts=opts.TitleOpts(title="各品类服饰年龄段分布"),
                             xaxis_opts=opts.AxisOpts(axislabel_opts=opts.LabelOpts(rotate=-25, interval=0, ))) # rotate=-25:标签逆时针旋转25°；interval=0:强制显示所有标签
    ).render("服饰年龄段分布.html")
    return c



